import { ref, onMounted } from 'vue'
import { exportXls, toLowerCase } from '@/utils'
import { ElMessage } from 'element-plus'
/**
 * @param {*查询接口} queryApi
 * @param {*查询参数} query
 * @param {*导出接口} exportApi
 * @param {*导出文件名} exportName
 * @param {*删除接口} deleteApi
 * @param {*自动请求} autoLoad
 */
export function useTable(options) {
  let {
    queryApi,
    query = {},
    exportApi,
    exportName,
    deleteApi,
    autoLoad = true
  } = options
  let queryCopy = JSON.parse(JSON.stringify(query))
  let commomQuery = {
    desc: query.desc,
    orderKey: query.orderKey || '',
    page: query.page || 1,
    pageSize: query.pageSize || 10
  }

  query = Object.assign(query, commomQuery)

  const tableData = ref([])
  const tableTotal = ref(0)

  const tableRef = ref(null)
  const downloading = ref(false)
  const getListAsync = async () => {
    let { code, data } = await queryApi({ ...query })
    if (code == 0) {
      let { list = [], total } = data
      tableData.value = list
      tableTotal.value = total
    }
  }

  const search = () => {
    query.page = 1
    getListAsync()
  }

  const reset = () => {
    query = Object.assign(query, queryCopy)
    query = Object.assign(query, commomQuery)
    search()
  }

  const exportListAsync = async () => {
    // downloading.value = true
    let response = await exportApi(query, onDownloadProgress)
    exportXls(response, exportName + '.xlsx')
  }

  const onDownloadProgress = (progress) => {
    // if (progress.target.response != null) {
    //   downloading.value = false
    // }
  }

  onMounted(() => {
    if (autoLoad) {
      getListAsync()
    }
  })

  const handleCurrentChange = (val) => {
    if (typeof val == 'number') {
      query.page = val
      getListAsync()
    }
  }

  const handleSizeChange = (val) => {
    query.pageSize = val
    search()
  }

  const selectItems = ref([])

  const handleSelectionChange = (val) => {
    selectItems.value = val
  }

  const handleSortChange = ({ column, prop, order }) => {
    if (order != null) {
      query.orderKey = toLowerCase(prop)
      query.desc = order === 'descending'
    } else {
      query.orderKey = ''
      query.desc = false
    }
    search()
  }

  const handleClearSelection = () => {
    selectItems.value = []
    tableRef.value.$children[0].clearSelection()
  }

  const deleteListAsync = async (callback, key = 'id') => {
    let ids = Array.isArray(selectItems.value)
      ? selectItems.value.map((_) => {
          return _[key]
        })
      : [selectItems.value[key]]

    let { code } = await deleteApi(ids)
    if (code == 0) {
      ElMessage.success('操作成功')
      getListAsync()
      callback()
    }
  }

  return {
    data: tableData,
    total: tableTotal,
    downloading,
    selectItems,
    tableRef,
    getListAsync,
    deleteListAsync,
    exportListAsync,
    search,
    reset,
    handleCurrentChange,
    handleSizeChange,
    handleSelectionChange,
    handleSortChange,
    handleClearSelection
  }
}
